package io.ent.modules.sys.controller;


import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

import io.ent.common.annotation.SysLog;
import io.ent.common.annotation.SysLoginLog;
import io.ent.common.gtsdk.GeetestConfig;
import io.ent.common.gtsdk.GeetestLib;
import io.ent.common.utils.IPUtils;
import io.ent.common.utils.R;
import io.ent.modules.sys.entity.SysUserEntity;
import io.ent.modules.sys.service.impl.SysUserServiceImpl;
import io.ent.modules.sys.shiro.ShiroUtils;

import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;

/**
 * 登录相关
 *
 * 
 */
@Controller
public class SysLoginController {
	@Autowired
	private Producer producer;
	@Autowired
	private SysUserServiceImpl sysUserServiceImpl;
	
	/*@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}*/

	//初始化极速验证API1
	@RequestMapping("/gtSdkInitialization")
	@ResponseBody
	public String gtSdkInitialization(HttpServletRequest request) {
		GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),
				GeetestConfig.isnewfailback());
		String resStr = "{}";
		String userid = "123456";  //测试
		String ip = IPUtils.getIpAddr(request);
		//自定义参数,可选择添加
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("user_id", userid); //网站用户id
		param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
		param.put("ip_address", ip); //传输用户请求验证时所携带的IP

		//进行验证预处理
		int gtServerStatus = gtSdk.preProcess(param);
		//将服务器状态设置到session中
		request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);
		//将userid设置到session中
		request.getSession().setAttribute("userid", userid);

		resStr = gtSdk.getResponseStr();
		return resStr;
	}

	//二次验证API2
	public int doubleGtSdkInitialization(HttpServletRequest request) {
		GeetestLib gtSdk = new GeetestLib(GeetestConfig.getGeetest_id(), GeetestConfig.getGeetest_key(),
				GeetestConfig.isnewfailback());

		String challenge = request.getParameter(GeetestLib.fn_geetest_challenge);
		String validate = request.getParameter(GeetestLib.fn_geetest_validate);
		String seccode = request.getParameter(GeetestLib.fn_geetest_seccode);

		//从session中获取gt-server状态
		int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
		//从session中获取userid
		String userid = (String)request.getSession().getAttribute("userid");
		String ip = IPUtils.getIpAddr(request);
		//自定义参数,可选择添加
		HashMap<String, String> param = new HashMap<String, String>();
		param.put("user_id", userid); //网站用户id
		param.put("client_type", "web"); //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
		param.put("ip_address", ip); //传输用户请求验证时所携带的IP

		int gtResult = 0;
		if (gt_server_status_code == 1) {
			//gt-server正常，向gt-server进行二次验证
			gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
		} else {
			// gt-server非正常情况下，进行failback模式验证
			System.out.println("failback:use your own server captcha validate");
//			gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
			System.out.println(gtResult);
		}
		return gtResult;

	}
	
	/**
	 * 登录
	 */
	@SysLoginLog("用户登录")
	@ResponseBody
	@RequestMapping(value = "/sys/login")
	public R login(String username, String password, String captcha, @RequestParam(value = "loginType",required=false)String loginType, HttpServletRequest request) {
//		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		/*if(!captcha.equalsIgnoreCase(kaptcha)){
			return R.error("验证码不正确");
		}*/
		if (loginType==null){
			int gt_server_status_code = (Integer) request.getSession().getAttribute("gt_server_status");
			if (gt_server_status_code!=1){
				return R.error("请点击按钮进行验证");
			}

			int result = doubleGtSdkInitialization(request);
			if (result!=1){
				return R.error("滑动验证失败");
			}
		}else {
			//进行人脸识别登录
			//识别通过，根据人脸id找到用户信息
			String faceId = "1";
			SysUserEntity sysUserEntity = sysUserServiceImpl.queryByFaceId(faceId);
			username = sysUserEntity.getUsername();
			password = "faceLogin";
		}

		try{
			Subject subject = ShiroUtils.getSubject();
			//把用户名、密码封装成一个UsernamePasswordToken对象
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			//去到 UserRealm 进行登陆认证
			subject.login(token);
		}catch (UnknownAccountException e) {
			return R.error(e.getMessage());
		}catch (IncorrectCredentialsException e) {
			return R.error("账号或密码不正确");
		}catch (LockedAccountException e) {
			return R.error("账号已被锁定,请联系管理员");
		}catch (AuthenticationException e) {
			return R.error("账户验证失败");
		}
	    
		return R.ok();
	}
	
	/**
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}
	
}
